package adc.budget.ui.web.wicket;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;

import adc.app.ui.wicket.BoEditPanel.ICancelCallback;
import adc.app.ui.wicket.BoEditPanel.ISaveCallback;
import adc.app.ui.wicket.model.BoModel;
import adc.budget.spec.bo.ICategory;
import adc.budget.spec.bs.ICategoryBs;
import adc.budget.ui.web.wicket.category.CategoryEditPanel;
import adc.budget.ui.web.wicket.category.CategoryListPanel;
import adc.budget.ui.web.wicket.category.IMsgsCategory;
import adc.budget.ui.web.wicket.category.CategoryListPanel.IAddClickedCallback;
import adc.budget.ui.web.wicket.category.CategoryListPanel.IEditClickedCallback;

public class CategoryPage extends LayoutPage implements IAddClickedCallback, IEditClickedCallback, ISaveCallback<ICategory>, ICancelCallback {
    private static final long serialVersionUID = 1L;

    private final CategoryListPanel listPanel;

    public CategoryPage() {
        super();
        listPanel = new CategoryListPanel("categories");
        listPanel.setAddClickedCallback(this).setEditClickedCallback(this);
        listPanel.setOutputMarkupId(true);
        add(listPanel);
        setTitle(new ResourceModel(IMsgsCategory.CATEGORIES));
    }


    @Override
    public void onEditClicked(AjaxRequestTarget target, ICategory category) {
        openEditDialog(target, BoModel.of(category, ICategoryBs.class));
    }

    @Override
    public void onAddClicked(AjaxRequestTarget target) {
       openEditDialog(target, BoModel.of(ICategoryBs.class));
    }

    @Override
    public void save(AjaxRequestTarget target, Form<ICategory> form) {
        ICategory cat = form.getModelObject();
        listPanel.save(target, cat);
        getModalWindow().close(target);
    }

    @Override
    public void cancel(AjaxRequestTarget target) {
        getModalWindow().close(target);
    }

    private void openEditDialog(final AjaxRequestTarget target, final IModel<ICategory> Category) {
        final ModalWindow md = getModalWindow();
        md.setContent(new CategoryEditPanel(md.getContentId()).setSaveCallback(this)
                .setCancelCallback(this).setModel(Category));
        md.setInitialWidth(300);
        md.setInitialHeight(220);
        md.setTitle(new ResourceModel(IMsgsCategory.CATEGORY));
        md.show(target);
    }

}
